<?php

namespace app\admin\controller\census;

use app\common\controller\Backend;
use think\Session;
use think\Db;

/**
 * 店铺管理
 *
 * @icon fa fa-circle-o
 */
class Payment extends Backend
{

    /**
     * Payment模型对象
     * @var \app\admin\model\census\Payment
     */
    protected $model = null;
    protected $order_model = null;
    protected $goods_order_model = null;
    protected $order_item_model = null;
    protected $count_order_model = null;

    //订单支付模型
    protected $pay_out_trade_model = null;
    protected $refund_model = null;

    protected $shop_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->shop_id = Session::get('shop');
        $this->model = new \app\admin\model\census\Payment;
        $this->order_model = new \app\admin\model\order\Order;
        $this->goods_order_model = new \app\admin\model\order\Goods;
        $this->order_item_model = new \app\admin\model\order\Item;
        $this->count_order_model = new \app\admin\model\census\Adate;
        $this->pay_out_trade_model = new \app\api\model\wanlshop\PayOutTrade;
        $this->refund_model = new \app\admin\model\wanlshop\Refund;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("verifyList", $this->model->getVerifyList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
             $conditions = '1=1';
            if ($this->shop_id != 1) {
                $conditions = ['payment.id' => $this->shop_id];
            }
            $list = $this->model
                    ->with(['order'])
                    ->where($where)
                    ->where($conditions)
                    ->order($sort, $order)
                    ->paginate($limit);

            if ($list->total() > 0) {
                $list_data = $list->items();
                foreach ($list_data as $key => &$value) {
                    $conditions = [];
                    $conditions['o.data_type'] = ['in',['cards','goods']];
                    $conditions['o.shop_id'] = $value['id'];
                    $conditions['o.state'] = ['in',['2','3','4','5','6']];//订单状态:1=待支付,2=待发货,3=待收货,4=待评论,5=售后订单(已弃用),6=已完成,7=已取消
                    $conditions['o.status'] = 'normal';
                    $conditions['po.pay_way_id'] = ['in',[10,11,12]];
                    $conditions['o.createtime'] = [['>=',$value['order']['adatetime']],['<=',$value['order']['adatetime'] + 3600 * 24 - 1]];

                    /** 景珍支付 start **/
                        //景珍支付收款
                        $value['lal_payment_amount'] = $this->order_model->alias('o')
                                                    ->join('wanlshop_pay_out_trade po','po.order_id = o.id','left')
                                                    ->where($conditions)
                                                    ->sum('o.actual_price');
                        
                        //景珍支付收款笔数
                        $value['lal_payment_count'] = $this->order_model->alias('o')
                                                    ->join('wanlshop_pay_out_trade po','po.order_id = o.id','left')
                                                    ->where($conditions)
                                                    ->count('o.id');
                        
                        //景珍支付退款
                        $conditions['o.state'] = '7';
                        $value['lal_refund_amount'] = $this->refund_model->alias('r')
                                                    ->join('wanlshop_order o','o.id = r.order_id','left')
                                                    ->join('wanlshop_pay_out_trade po','po.order_id = r.order_id','left')
                                                    ->where($conditions)
                                                    ->sum('r.price');

                        //景珍支付退款笔数
                        $value['lal_refund_count'] = $this->refund_model->alias('r')
                                                    ->join('wanlshop_order o','o.id = r.order_id','left')
                                                    ->join('wanlshop_pay_out_trade po','po.order_id = r.order_id','left')
                                                    ->where($conditions)
                                                    ->count('r.order_id');
                    /** 景珍支付 end **/

                    /** 现金(记账) start **/
                        //现金(记账)收款
                        $conditions['o.state'] = ['in',['2','3','4','5','6']];
                        $conditions['po.pay_way_id'] = ['in',[6,7,8]];
                        $value['cash_payment_amount'] = $this->order_model->alias('o')
                                                        ->join('wanlshop_pay_out_trade po','po.order_id = o.id','left')
                                                        ->where($conditions)
                                                        ->sum('o.actual_price');

                        //现金(记账)收款笔数
                        $value['cash_payment_count'] = $this->order_model->alias('o')
                                                        ->join('wanlshop_pay_out_trade po','po.order_id = o.id','left')
                                                        ->where($conditions)
                                                        ->count('o.id');

                        //现金(记账)退款
                        $conditions['o.state'] = '7';
                        $value['cash_refund_amount'] = $this->refund_model->alias('r')
                                                        ->join('wanlshop_order o','o.id = r.order_id','left')
                                                        ->join('wanlshop_pay_out_trade po','po.order_id = r.order_id','left')
                                                        ->where($conditions)
                                                        ->sum('r.price');

                        //现金(记账)退款笔数
                        $value['cash_refund_count'] = $this->refund_model->alias('r')
                                                        ->join('wanlshop_order o','o.id = r.order_id','left')
                                                        ->join('wanlshop_pay_out_trade po','po.order_id = r.order_id','left')
                                                        ->where($conditions)
                                                        ->count('r.order_id');
                    /** 现金(记账) end **/

                    /** 余额 start **/
                        //余额收款
                        $conditions['o.state'] = ['in',['2','3','4','5','6']];
                        $conditions['po.pay_way_id'] = 9;
                        $value['balance_payment_amount'] = $this->order_model->alias('o')
                                                        ->join('wanlshop_pay_out_trade po','po.order_id = o.id','left')
                                                        ->where($conditions)
                                                        ->sum('o.actual_price');

                        //余额收款笔数
                        $value['balance_payment_count'] = $this->order_model->alias('o')
                                                        ->join('wanlshop_pay_out_trade po','po.order_id = o.id','left')
                                                        ->where($conditions)
                                                        ->count('o.id');

                        //余额退款
                        $conditions['o.state'] = '7';
                        $value['balance_refund_amount'] = $this->refund_model->alias('r')
                                                        ->join('wanlshop_order o','o.id = r.order_id','left')
                                                        ->join('wanlshop_pay_out_trade po','po.order_id = r.order_id','left')
                                                        ->where($conditions)
                                                        ->sum('r.price');

                        //余额退款笔数
                        $value['balance_refund_count'] = $this->refund_model->alias('r')
                                                        ->join('wanlshop_order o','o.id = r.order_id','left')
                                                        ->join('wanlshop_pay_out_trade po','po.order_id = r.order_id','left')
                                                        ->where($conditions)
                                                        ->count('r.order_id');
                    /** 余额 end **/

                    //实收金额
                    $conditions['o.state'] = ['in',['2','3','4','5','6']];
                    unset($conditions['po.pay_way_id']);
                    $value['total_amount'] = $this->order_model->alias('o')
                                                ->where($conditions)
                                                ->sum('o.actual_price');
                                                
                    //实收笔数
                    $value['total_count'] = $this->order_model->alias('o')
                                            ->where($conditions)
                                            ->count('o.id');
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail()
    {
        $params = $this->request->get();
        $shop_id = $params['shop_id'];
        $createtime = $params['createtime'];

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $params = $this->request->get();
            $shop_id = $params['shop_id'];
            $createtime = $params['createtime'];
            $conditions = [];
            $conditions['o.data_type'] = ['<>','merchant'];
            $conditions['o.shop_id'] = $shop_id;
            $conditions['o.status'] = 'normal';
            $conditions['o.state'] = 6;
            $conditions['o.createtime'] = [['>=',$createtime],['<=',$createtime + 3600 * 24 - 1]];
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if (isset($params['filter']) && !empty($params['filter'])) {
                $filter = json_decode($params['filter'],true);
                if (isset($filter['order_no'])) {
                    $conditions['o.order_no'] = ['like','%'.$filter['order_no'].'%'];
                }

                if (isset($filter['order_type'])) {
                    if ($filter['order_type'] == 0) {
                        $conditions[] = ['exp', Db::raw("r.id IS NOT NULL")];
                    }else{
                        $conditions[] = ['exp', Db::raw("r.id IS NULL")];
                    }
                    
                }

                if (isset($filter['pay_way_id'])) {
                    $conditions['p.pay_way_id'] = $filter['pay_way_id'];
                }
            }

            $list = $this->order_model->alias('o')
                    ->field("distinct(o.id), o.order_no as order_no,o.data_type,r.id as ref_id,o.dealtime,p.pay_way_id,o.actual_price as amount,p.out_trade_no,IF(r.id,'0','1') AS order_type,w.name")
                    ->where($conditions)
                    ->join('wanlshop_pay_out_trade p','p.order_id = o.id','left')
                    ->join('pay w','w.id = p.pay_way_id','left')
                    ->join('wanlshop_refund r','r.order_id = o.id','left')
                    ->paginate($limit);
                  // echo  $this->order_model->getlastsql();die;
            $total = $list->total();
            $rows = $list->items();

            if ($total > 0) {
                foreach ($rows as $key => &$value) {
                    $value['j_url'] = url('/order/goodsorder/detail/ids/'.$value["id"]);
                    if ($value['data_type'] == 'cards') {
                        $value['j_url'] = url('/order/itemorder/detail/ids/'.$value["id"]);
                    }
                }
            }

            $result = array("total" => $total, "rows" => $rows);
            return json($result);
        }
        $this->assignconfig('shop_id', $shop_id);
        $this->assignconfig('createtime', $createtime);
        return $this->view->fetch();
    }
}
